package cn.imatu.framework.tool.core.file;

import cn.hutool.http.ContentType;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.imatu.framework.tool.core.exception.UtilException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;

/**
 * @author shenguangyang
 */
@Slf4j
public class MultipartFileUtil {
    /**
     * 输入流转MultipartFile
     */
    public static MultipartFile getMultipartFile(String fileName, InputStream inputStream) {
        try {
            return new MockMultipartFile(fileName, fileName, ContentType.OCTET_STREAM.getValue(), inputStream);
        } catch (Exception e) {
            log.error("error: ", e);
            throw new UtilException("文件流转换失败");
        }
    }

    /**
     * 读取网络文件
     *
     * @param url      文件地址
     * @param fileName 文件名称（需带文件名后缀）
     */
    public static MultipartFile getMultipartFile(String url, String fileName) {
        HttpRequest httpRequest = HttpRequest.get(url);
        try (HttpResponse response = httpRequest.execute()) {
            InputStream inputStream = response.bodyStream();
            return MultipartFileUtil.getMultipartFile(fileName, inputStream);
        }
    }
}
